<template>
  <div v-if="row || value"
       :class="{'red': flags}">
    <p>{{ `${shipperAddressrmation.province || ''}${shipperAddressrmation.city || ''}${shipperAddressrmation.district || ''}` }}</p>
    <p>{{ optimizedAddress }}</p>
  </div>
</template>

<script>
/**
 * @value 发货方运单信息配置
 * @FileDescription 为什么运单的需要value配置而订单不需要，是因为数据结构不同，订单信息会包一层
 * @param {Object} {
 *  "province": "${fromProvince}",
 *  "city": "${fromCity}",
 *  "district": "${fromDistrict}"
 *  "address": "${fromAddress}"
 * }
 * **/

function removeProvinceCityDistrict (address, province, city, district) {
  if (typeof address !== 'string') {
    return '';
  }
  // 正则表达式匹配，同时包含省、市和区
  let provinceCityDistrictRegex = new RegExp(province + ".*" + city + ".*" + district, "g");
  let cleanedAddress = address?.replace(provinceCityDistrictRegex, "");
  // 去除字符串开头和结尾的斜杠
  cleanedAddress = cleanedAddress?.replace(/^\//, "").replace(/\/$/, "");
  return cleanedAddress;
}

export default {
  name: 'ShipmentSenderAddress',
  props: {
    row: {
      type: Object,
      default: () => { }
    },
    value: {
      type: Object,
      default: () => { }
    },
    flag: {
      type: [String, Function],
      default: ""
    }
  },
  data () {
    return {
      optimizedAddress: null
    }
  },
  computed: {
    shipperAddressrmation () {
      return this.value || this.optimizeFromAddress
    },
    optimizeFromAddress () {
      const { fromAddress } = this.row;
      const optimizeFromAddress = {
        province: fromAddress?.province || '',
        city: fromAddress?.city || '',
        district: fromAddress?.district || ''
      };
      return optimizeFromAddress;
    },
    address () {
      return this.value ? this.value?.address : this.row?.fromAddress?.address
    },
    // optimizedAddress () {
    //   const { province, city, district } = this.shipperAddressrmation
    //   const optimizedAddress = removeProvinceCityDistrict(this.address, province, city, district)
    //   return optimizedAddress;
    // },
    defaults () {
      return true
    },
    flags () {
      return this.flag || ''
    }
  },
  watch: {
    row: {
      deep: true,
      immediate: true,
      handler (value) {
        const { province, city, district } = this.shipperAddressrmation
        this.optimizedAddress = removeProvinceCityDistrict(this.address, province, city, district)
      }
    }
  }
}
</script>

<style scoped>
p {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin: 0 !important;
}
.red {
  color: var(--prev-color-text-red) !important;
}
.red >>> p {
  margin: 0 !important;
}
</style>